#pragma indent
using System.IO
using System.Text.RegularExpressions
using Nemerle.IO
using Nemerle.Collections

public class Main
    public static Main(args: array[string]): void

        def moduleUnderTest(testModule)
            def testDir = Path.GetDirectoryName(testModule)
            def parentDir = Path.GetDirectoryName(testDir)
            def testName = Path.GetFileNameWithoutExtension(testModule)
            def moduleName = testName.Substring(0, testName.Length - 4)
            Path.Combine(parentDir, moduleName + ".py")

        def compileDictionary(file)
            def dict = Hashtable()
            def reader = File.OpenText(file)
            while(reader.Peek() >= 0)
                def line = reader.ReadLine()
                foreach(word in line.Split(' ', '(', ')', ',', '.', '"', '\''))
                    def lowerWord = word.ToLower()
                    when (!dict.ContainsKey(lowerWord))
                        dict[lowerWord] = word
            reader.Close()
            dict

        def testLine = Regex("^    def (test[^(]*)\\(self\\): *", RegexOptions.Compiled)

        def getTestName(line)
            testLine.Match(line).Groups[1].Value

        foreach(file in args)
            def testNamesUsed = Hashtable()
            def mut = moduleUnderTest(file)
            def dictionary = if (File.Exists(mut))
                compileDictionary(mut) 
            else
                Hashtable()
            mutable output = []
            foreach(line in File.ReadAllLines(file))
                if(testLine.IsMatch(line) )
                    def testName = getTestName(line)
                    def truncated = SplitCamelCase.First4Components(testName)
                    def n = testNamesUsed.GetValueOrDefault(truncated, 1)
                    testNamesUsed[truncated] = n + 1
                    def uniqueTruncated = if (n > 1) 
                        truncated + n.ToString()
                    else
                        truncated
                    def newLine = line.Replace(testName, uniqueTruncated)
                    output ::= newLine
                    when (testName != truncated)
                        def comment = SplitCamelCase.Split(testName, dictionary)
                        output ::= $"        \"$comment\""
                else
                    output ::= line
            output = output.Reverse()
            File.WriteAllLines(file, output.ToArray())
                
